package com.qf.xiaomi.dao.impl;

import com.qf.xiaomi.dao.AddressDao;
import com.qf.xiaomi.pojo.Address;
import com.qf.xiaomi.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class AddressDaoImpl implements AddressDao {
    @Override
    public List<Address> getAddList(int uid) {
        QueryRunner qr  = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from tb_address where uid = ?";
        List<Address> addrList = null;
        try {
            addrList = qr.query(sql, new BeanListHandler<>(Address.class), uid);
            return addrList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void addAddress(Address address) {
        QueryRunner qr  = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "INSERT INTO `tb_address` ( `detail`, `name`, `phone`, `uid`, `level`) VALUES ( ?, ?, ?, ?, ?)";
        try {
            qr.update(sql , address.getDetail(), address.getName(), address.getPhone(),address.getUid(),address.getLevel());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(int id) {
        QueryRunner qr  = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "delete from tb_address where id = ?";
        try {
            qr.update(sql , id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(Address address) {
        QueryRunner qr  = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "UPDATE `tb_address` SET  `detail` = ?, `name`=?, `phone`=? WHERE (`id`=?)";
        try {
            qr.update(sql , address.getDetail(), address.getName(), address.getPhone(),address.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void set2Normal(int uid) {
        QueryRunner qr  = new QueryRunner();
        String sql = "UPDATE `tb_address` SET  level = 0 WHERE (`uid`=?)";
        try {
            qr.update(DataSourceUtils.getConnection(), sql , uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setDefaultAddress(String aId) {
        QueryRunner qr  = new QueryRunner();
        String sql = "UPDATE `tb_address` SET  level = 1 WHERE (`id`=?)";
        try {
            qr.update(DataSourceUtils.getConnection(), sql , aId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
